#include "TWI.h"

void TWI_init(void){
	DDRC &=!((1<<PC0)|(1<<PC1));
	PORTC = (1<<PC0)|(1<<PC1);
  	TWSR = 0;                        							// no prescaler
  	TWBR = ((F_CPU/SCL_CLOCK)-16)/2;  							// must be > 10 for stable operation	
}

uint8_t TWI_start(uint8_t address){
    uint8_t   twst;

	TWCR = (1<<TWINT) | (1<<TWSTA) | (1<<TWEN);					// send START condition

	while(!(TWCR & (1<<TWINT)));								// wait until transmission completed

	twst = TW_STATUS & 0xF8;									// check value of TWI Status Register. Mask prescaler bits.
	if ( (twst != TW_START) && (twst != TW_REP_START)) 
		return 1;
	
	TWDR = address;												// send device address
	TWCR = (1<<TWINT) | (1<<TWEN);
	
	while(!(TWCR & (1<<TWINT)));								// wail until transmission completed and ACK/NACK has been received
		
	twst = TW_STATUS & 0xF8;									// check value of TWI Status Register. Mask prescaler bits.
	if ( (twst != TW_MT_SLA_ACK) && (twst != TW_MR_SLA_ACK) ) 	
		return 1;												// failed
	return 0;													// successful
}

void TWI_stop(void){
    
	TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWSTO);					// send stop condition
	
	while(TWCR & (1<<TWSTO));									// wait until stop condition is executed and bus released
}

uint8_t TWI_readAck(void){
	TWCR = (1<<TWINT) | (1<<TWEN) | (1<<TWEA);
	while(!(TWCR & (1<<TWINT)));    

    return TWDR;
}

uint8_t TWI_readNak(void){
	TWCR = (1<<TWINT) | (1<<TWEN);
	while(!(TWCR & (1<<TWINT)));
	
    return TWDR;
}
